/*
 * @Author: C.
 * @Date: 2023-04-24 14:36:55
 */
// 管理税率
import { ref, unref } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';

import { get_all_customer } from '/@/api/work/sale/customer';
import { useMessage } from '/@/hooks/web/useMessage';

import { get_all_supplier } from '/@/api/work/purchase/supplier';
// customer supplier  CustomerId = '', SupplierId = ''
export function useTax(type: 'customer' | 'supplier' = 'customer') {
  const taxRef = ref<number>(0);
  const idRef = ref<string>();
  const { createConfirm } = useMessage();
  const { t } = useI18n();
  async function taxChange(id: string) {
    console.log(id, 'id');

    if (id === unref(idRef)) return;
    idRef.value = id;
    const tax = await fetch();
    taxRef.value = tax;
  }
  function getTax() {
    return unref(taxRef);
  }
  async function taxChangeWarning(id: string, func: Fn, key = 'Tax') {
    console.log(id, unref(idRef));

    if (id === unref(idRef)) return;
    // 防止当前无id 显示操作提示
    const _cur = unref(idRef);
    idRef.value = id;
    const tax = await fetch();
    if (tax === unref(taxRef)) return;
    taxRef.value = tax;
    console.log(tax, 'tax');
    if (_cur) {
      createConfirm({
        title: t('common.operationalAlerts'),
        content: () => '当前单据的客户或者供应商有变，是否将该单据明细的税率全部替换？',
        onOk: () => func(key, tax),
        iconType: 'warning',
      });
    } else {
      func(key, tax);
    }
  }
  async function fetch() {
    if (!unref(idRef)) return;
    let target: Recordable = {};
    if (type === 'supplier') {
      const res = await get_all_supplier();
      target = res.Items.find((item) => item.SupplierId === idRef.value);
    } else {
      const res = await get_all_customer();
      target = res.Items.find((item) => item.CustomerId === idRef.value);
    }
    if (target) {
      return target.Tax;
    }
  }
  return {
    getTax,
    taxChange,
    taxChangeWarning,
  };
}
